package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;  //获取四个参数

    @Autowired
    private UserMapper userMapper;

    //微信服务调用接口i地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //调用微信服务接口，获得当前登录凭证code对应的openid  封装成一个方法getOpenId了

        String openid = getOpenId(userLoginDTO.getCode());

        //判断openid是否为空，为空则不合法,抛出异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //如果openid不存在于数据库，如果不在说明需要注册，插入数据             //封装返回的User对象
        User user = userMapper.getByopenId(openid);

        if(user == null){
            //新用户，需要插入
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);                    //由于在Usercontroller中使用到了主键id，所以要添加两个xml中的sql属性
        }

        return user;
    }


    //调用微信接口服务获取openid
    private String getOpenId(String code){
        Map<String,String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",code);    //从小程序请求带过来的凭证code
        param.put("grant_type","authorization_code");

        String s = HttpClientUtil.doGet(WX_LOGIN, param);   //返回的内容可由微信登录官方文档具体查看,解析json字符串

        JSONObject jsonObject = JSON.parseObject(s);  //解析返回的json字符串
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
